package com.example.demo.threadTest;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static cn.hutool.core.thread.ThreadUtil.newCountDownLatch;
import static java.util.concurrent.Executors.*;

/**
 * @author leiliang
 * @version 1.0
 * @Description CountDownLatch +  ExecutorService
 * @date 2022/8/12 16:25
 */
public class CountDownTest {


    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = newCountDownLatch(5);
        ExecutorService service = newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            final int no = i + 1;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep((long) (Math.random() * 20000));
                        System.out.println(no + "号运动员完成了比赛。");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            };
            service.submit(runnable);
        }
        System.out.println("等待5个运动员都跑完.....");
        latch.await();
        System.out.println("所有人都跑完了，比赛结束。");
    }
}